package com.alone.wchat.wxBackend.web;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.alone.wchat.wxBackend.utils.TimeUtils;
import com.cybermkd.mongo.kit.MongoQuery;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.api.TemplateMsgApi;
import com.jfinal.weixin.sdk.jfinal.MsgControllerAdapter;
import com.jfinal.weixin.sdk.msg.in.InTextMsg;
import com.jfinal.weixin.sdk.msg.in.event.InFollowEvent;
import com.jfinal.weixin.sdk.msg.in.event.InMenuEvent;
import com.jfinal.weixin.sdk.msg.out.OutTextMsg;
import com.mongodb.client.MongoCollection;
import net.dreamlu.weixin.annotation.WxMsgController;
import net.dreamlu.weixin.properties.DreamWeixinProperties;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;

import java.util.Date;
import java.util.List;

/**
 * created by weirdor on 2018/4/20
 */
@WxMsgController("/weixin/wx")
@Scope("prototype")
public class WeixinController extends MsgControllerAdapter {

    @Autowired
    private DreamWeixinProperties weixinProperties;

    private static final String helpStr = "\t你的品位不错哦  么么哒 -By weirdor。";


    @Override
    protected void processInFollowEvent(InFollowEvent inFollowEvent) {
        OutTextMsg outMsg = new OutTextMsg(inFollowEvent);
        outMsg.setContent("关注消息~");
        render(outMsg);
    }

    @Override
    protected void processInTextMsg(InTextMsg inTextMsg) {
        OutTextMsg outMsg = new OutTextMsg(inTextMsg);
        String LocalTime= getLocationTime(inTextMsg.getContent());
        if (LocalTime==null){
            outMsg.setContent("请重新输入城市名！！！");
            render(outMsg);
        }else {
            Date localDate = DateUtil.parse(LocalTime, "yyyy-MM-dd HH:mm:ss");
            String msgContent = inTextMsg.getContent().trim();
            System.out.println(msgContent);
            System.out.println(weixinProperties.getAppIdKey());

            outMsg.setContent(LocalTime);
            render(outMsg);
        }

    }

    @Override
    protected void processInMenuEvent(InMenuEvent inMenuEvent) {
        OutTextMsg outMsg = new OutTextMsg(inMenuEvent);
        outMsg.setContent("菜单消息~");
        render(outMsg);
    }


    /**
     * 根据国家获取当地时间
     * */
    public  String getLocationTime(String country){
        MongoQuery query=new MongoQuery();
        List<JSONObject> doc=query.use("cityInfo").eq("city_cn",country).find();
        if (doc.size()<=0){
            return  null;
        }
        return TimeUtils.getLocalDatetimeString("GMT"+doc.stream().findFirst().get().getString("time_zone_no"));
    }
}